package com.aliwo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author:xuyayuan
 * @date:2021/7/14 23:01
 * @description: 登录过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 功能描述:过滤器类型
     * @author xuyayuan
     * @param
     * @return java.lang.String
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 功能描述:过滤器执行顺序，值越小越先执行
     * @author xuyayuan
     * @param
     * @return int
     */
    @Override
    public int filterOrder() {
        return 4;
    }

    /**
     * 功能描述:过滤器是否生效
     * @author xuyayuan
     * @param
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        // 针对订单接口进行过滤，执行run()方法,其他接口不执行过滤run()方法
        if ("/apigetway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())) {
            return true;
        }
        return false;
    }

    /**
     * 功能描述:书写自己的业务逻辑
     * @author xuyayuan
     * @param
     * @return java.lang.Object
     */
    @Override
    public Object run() throws ZuulException {
        // JWT技术
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 登录校验逻辑
        if (StringUtils.isBlank(token)) {
            // zuul不往下执行了
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
